#include "FunctionProtocolGenerator.h"
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include "ProtocolConfigManager.h"

FunctionProtocolGenerator::FunctionProtocolGenerator(QObject *parent)
    : QObject(parent)
{

}

QVariantMap FunctionProtocolGenerator::generateCommand(const QVariantMap &protocolConfig, const QVariantMap &params)
{
    // 参数验证
    if (protocolConfig.isEmpty()) {
        qWarning() << "Protocol config cannot be empty";
        return QVariantMap();
    }

    // 从协议配置中提取必要信息
    QString functionName = protocolConfig["functionName"].toString();
    if (functionName.isEmpty()) {
        qWarning() << "Function name not found in protocol config";
        return QVariantMap();
    }

    QString deviceId = protocolConfig["deviceId"].toString();
    if (deviceId.isEmpty()) {
        qWarning() << "Device ID not found in protocol config";
        return QVariantMap();
    }

    // 获取参数配置
    QVariantList paramConfigs = protocolConfig["parameters"].toList();
    if (paramConfigs.isEmpty()) {
        qWarning() << "No parameters defined in protocol config for function:" << functionName;
    }

    // 按顺序处理参数
    QVariantMap orderedParams;
    for (const QVariant &paramConfigVar : paramConfigs) {
        QVariantMap paramConfig = paramConfigVar.toMap();
        QString paramName = paramConfig["name"].toString();

        // 检查参数是否为变量
        if (paramConfig.value("variable", true).toBool()) {
            // 变量参数：从传入的params中获取
            if (params.contains(paramName)) {
                orderedParams[paramName] = params[paramName];
            } else {
                qWarning() << "Missing parameter:" << paramName << "for function:" << functionName;
                // 可以选择返回空或使用默认值
            }
        } else {
            // 常量参数：直接使用配置中的值
            if (paramConfig.contains("value")) {
                orderedParams[paramName] = paramConfig["value"];
            } else {
                qWarning() << "Constant parameter" << paramName << "has no value defined";
            }
        }
    }

    // 创建返回的函数调用信息
    QVariantMap result;
    result["functionName"] = functionName;
    result["params"] = orderedParams;
    result["deviceId"] = deviceId;

    // 可选：添加其他有用信息
    if (protocolConfig.contains("return_type")) {
        result["returnType"] = protocolConfig["return_type"];
    }

    return result;
}

QString FunctionProtocolGenerator::formatParams(const QVariantMap &params, const QVariantList &paramConfigs)
{
    QStringList paramStrings;

    // 如果提供了参数配置，按配置顺序处理
    if (!paramConfigs.isEmpty()) {
        for (const QVariant &paramConfigVar : paramConfigs) {
            QVariantMap paramConfig = paramConfigVar.toMap();
            QString paramName = paramConfig["name"].toString();

            if (params.contains(paramName)) {
                paramStrings.append(paramName + "=" + variantToString(params[paramName]));
            }
        }
    } else {
        // 没有参数配置，使用传入的参数顺序
        for (auto it = params.constBegin(); it != params.constEnd(); ++it) {
            paramStrings.append(it.key() + "=" + variantToString(it.value()));
        }
    }

    return paramStrings.join(", ");

};

QString FunctionProtocolGenerator::formatParams(const QVariantMap &params)
{
    QStringList paramStrings;
    for (auto it = params.constBegin(); it != params.constEnd(); ++it) {
        // 参数格式: 名称=值
        paramStrings.append(it.key() + "=" + variantToString(it.value()));
    }
    return paramStrings.join(", ");
}

QString FunctionProtocolGenerator::variantToString(const QVariant &param)
{
    if (param.type() == QVariant::Int || param.type() == QVariant::UInt ||
        param.type() == QVariant::LongLong || param.type() == QVariant::ULongLong) {
        return QString::number(param.toLongLong());
    } else if (param.type() == QVariant::Double) {
        return QString::number(param.toDouble(), 'g', 15);
    } else if (param.type() == QVariant::Bool) {
        return param.toBool() ? "true" : "false";
    } else if (param.type() == QVariant::String) {
        // 字符串需要添加引号
        QString str = param.toString();
        // 转义双引号
        str.replace("\"", "\\\"");
        return "\"" + str + "\"";
    } else if (param.type() == QVariant::ByteArray) {
        // 字节数组转换为十六进制字符串
        return "0x" + param.toByteArray().toHex();
    } else if (param.canConvert<QVariantMap>()) {
        // 转换为JSON对象字符串
        QVariantMap map = param.toMap();
        QJsonDocument doc(QJsonObject::fromVariantMap(map));
        QString jsonStr = QString::fromUtf8(doc.toJson(QJsonDocument::Compact));
        return jsonStr;
    } else if (param.canConvert<QVariantList>()) {
        // 转换为JSON数组字符串
        QVariantList list = param.toList();
        QJsonDocument doc(QJsonArray::fromVariantList(list));
        QString jsonStr = QString::fromUtf8(doc.toJson(QJsonDocument::Compact));
        return jsonStr;
    } else {
        // 未知类型，转换为字符串
        return param.toString();
    }
}
